// Sam2Parser.js
const COCOLabelLoader = require('../../../../../labels/vision/detection/COCOLabelLoader');

class Sam2Parser {
    constructor(app) {
        this.app = app;
        this.loader = new COCOLabelLoader(this.app);
    }

    // 解析返回的结果（只是转换格式）
    convertResult(result) {
        // console.log(`>> Sam2Parser convertResult segs'length = `, result['det_node.segs'].length);
        // "output": ["det_node.bboxes", "det_node.labels", "det_node.segs", "det_node.scores"],
        // grounding dino返回的是中心点和宽高
        const bboxes = [];
        for (let i = 0; i < result['det_node.bboxes'].length; i++) {
            const bbox = result['det_node.bboxes'][i];
            bbox[2] = bbox[2] - bbox[0];
            bbox[3] = bbox[3] - bbox[1];
            bboxes.push(bbox);
        }

        // 将seg的坐标转换为coco格式
        const segs = [];
        for (let i = 0; i < result['det_node.segs'].length; i++) {
            const seg = result['det_node.segs'][i];
            const seg_coco = [];
            for (let j = 0; j < seg.length; j++) {
                const polyline = [];
                for (let k = 0; k < seg[j].length; k++) {
                    polyline.push(seg[j][k][1]);
                    polyline.push(seg[j][k][0]);
                }
                seg_coco.push(polyline);
            }
            segs.push(seg_coco);
        }

        // 调用具体的转换函数
        let labelResult = this.loader.create(bboxes, segs, result['det_node.labels'], result['det_node.scores']);
        // console.log(`labelResult = `, labelResult);
        return labelResult;
    }

    // 解析返回的结果（保存结果）
    // datasetInfo：数据集信息  
    // recordInfo：存储的记录
    // result：解析的结果
    async saveResult(datasetInfo, recordInfo, result) {
        console.log(`>> Sam2Parser saveResult datasetInfo = `, datasetInfo, `recordInfo = `, recordInfo, `result = `, result);
        return result;
    }
}

module.exports = Sam2Parser;
